package com.monolithiot.cdn.management.service.impl;

import com.monolithiot.cdn.management.common.entity.Project;
import com.monolithiot.cdn.management.common.entity.User;
import com.monolithiot.cdn.management.common.util.UploadFileUtil;
import com.monolithiot.cdn.management.common.util.ZipUtil;
import com.monolithiot.cdn.management.config.UploadPathConfigure;
import com.monolithiot.cdn.management.dao.BaseMapper;
import com.monolithiot.cdn.management.dao.mapper.ProjectMapper;
import com.monolithiot.cdn.management.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.zip.ZipInputStream;

/**
 * 2018/11/20 Create by 郭文梁
 * ProjectServiceImpl
 * 项目业务行为实现
 *
 * @author 郭文梁
 * @date 2018/11/20
 */
@Service
@Slf4j
public class ProjectServiceImpl extends BaseServiceImpl<Project> implements ProjectService {
    private final ProjectMapper projectMapper;
    private final UploadPathConfigure uploadPathConfigure;

    @Autowired
    public ProjectServiceImpl(ProjectMapper projectMapper, UploadPathConfigure uploadPathConfigure) {
        this.projectMapper = projectMapper;
        this.uploadPathConfigure = uploadPathConfigure;
    }

    @Override
    BaseMapper<Project> getMapper() {
        return projectMapper;
    }

    @Override
    public Project create(Project project, User user) {
        Project target = new Project();
        target.setContextPath(project.getContextPath());
        target.setName(project.getName());
        target.setCreateTime(new Date());
        target.setNote(project.getNote());
        target.setUserId(user.getId());

        //默认项目保存路径与ContextPath相同
        target.setTargetPath(project.getContextPath());
        return save(target);
    }

    @Override
    public Project setZipFile(Project project, MultipartFile zipFile) throws IOException {
        String cdnFilePath = uploadPathConfigure.getCdnFilePath();
        String filename = UploadFileUtil.copyTmpToPath(zipFile, cdnFilePath);
        project.setZipFile(filename);
        return update(project);
    }

    @Override
    public Project unzip(Project project) throws IOException {
        String cdnFilePath = uploadPathConfigure.getCdnFilePath();
        String zipFile = project.getZipFile();
        File file = new File(cdnFilePath, zipFile);
        if (!file.exists()) {
            throw new FileNotFoundException(String.format("File of Project %s not fond", project.getName()));
        }

        String targetPath = uploadPathConfigure.getCdnFilePath() + project.getTargetPath();

        int unzipCount = ZipUtil.unzip(file, targetPath);
        log.debug("Unzip file count: {}", unzipCount);
        return project;
    }
}
